package com.orchid.community.models.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.orchid.community.common.exceptions.CustomException;
import com.orchid.community.common.utils.CodeEnum;
import com.orchid.community.common.utils.MD5Util;
import com.orchid.community.common.utils.MsgResponse;
import com.orchid.community.common.utils.ResultUtils;
import com.orchid.community.models.DTO.AccountParam;
import com.orchid.community.models.DTO.UserParamDTO;
import com.orchid.community.models.DTO.UserParamRequestDTO;
import com.orchid.community.models.DTO.UserRequestDTO;
import com.orchid.community.models.entity.SysUsers;
import com.orchid.community.models.mapper.AccountMapper;
import com.orchid.community.models.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;

@Service
public class AccountServiceImpl  implements AccountService {


    @Autowired
    private AccountMapper accountMapper;

    @Override
    public MsgResponse getAccountList(UserParamDTO userParamDTO) {
        PageHelper.startPage(userParamDTO.getPageNo(), userParamDTO.getPageSize());
        List<UserParamRequestDTO> pageList = accountMapper.getAccountList();
        for (UserParamRequestDTO userRequestDTO : pageList) {
            String permissionStr = userRequestDTO.getPermissionStr();
            if(permissionStr != null){
                List<String> permissionList = new ArrayList<>(Arrays.asList(permissionStr.split(",")));
                System.out.println(permissionList);
                Map<String, String> removalMap = new HashMap<>();
                removalMap.put("Order", "Details");
                removalMap.put("LaterWork", "LaterDetails");
                removalMap.put("Channel", "CreateChannel");
                // 遍历映射，并根据键值对执行删除
                for (Map.Entry<String, String> entry : removalMap.entrySet()) {
                    if (permissionList.contains(entry.getKey())) {
                        permissionList.remove(entry.getValue());
                    }
                }
                userRequestDTO.setPermission(permissionList);
            }
        }
        PageInfo<UserParamRequestDTO> pageInfo = new PageInfo<>(pageList);
        System.out.println(pageInfo);
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("count", pageInfo.getTotal());
        resultMap.put("list", pageInfo.getList());
        return ResultUtils.success(resultMap);
    }

    @Override
    public MsgResponse addAccount(AccountParam accountParam) {
        String username = accountParam.getUsername();
        String userByUsername = accountMapper.getUserByUsername(username);
        if(userByUsername != null){
            return ResultUtils.fail(CodeEnum.ACCOUNT_REPEAT);
        }
        List<String> additionalPermissions = new ArrayList<>();
        List<String> permissionList = accountParam.getPermission();
        for (String router : permissionList) {
            if(router.equals("Order")){
                additionalPermissions.add("Details");
            }
            if(router.equals("LaterWork")){
                additionalPermissions.add("LaterDetails");
            }
            if(router.equals("Channel")){
                additionalPermissions.add("CreateChannel");
            }
        }
        permissionList.addAll(additionalPermissions);
        String permission = String.join(",", permissionList);
        String password = MD5Util.MD5(accountParam.getUsername());
        SysUsers sysUsers = new SysUsers();
        sysUsers.setUsername(accountParam.getUsername());
        sysUsers.setName(accountParam.getName());
        sysUsers.setPhone(accountParam.getPhone());
        sysUsers.setPermission(permission);
        sysUsers.setPassword(password);
        sysUsers.setFreeze(0);
        sysUsers.setStatus(0);
        sysUsers.setUserRole(2);
        int flag = accountMapper.addAccount(sysUsers);
        if(flag != 1){
            return ResultUtils.fail(CodeEnum.ADD_FAIL);
        }
        return ResultUtils.success("OK");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MsgResponse editAccount(AccountParam accountParam) {
        String oldUsername = getUsernameById(Integer.valueOf(accountParam.getId()));
        if(!accountParam.getUsername().equals(oldUsername)){
            String username = accountParam.getUsername();
            String userByUsername = accountMapper.getUserByUsername(username);
            if(userByUsername != null){
                return ResultUtils.fail(CodeEnum.ACCOUNT_REPEAT);
            }
        }
        List<String> permissionList = accountParam.getPermission();
        List<String> additionalPermissions = new ArrayList<>();
        for (String router : permissionList) {
            if(router.equals("Order")){
                additionalPermissions.add("Details");
            }
            if(router.equals("LaterWork")){
                additionalPermissions.add("LaterDetails");
            }
            if(router.equals("Channel")){
                additionalPermissions.add("CreateChannel");
            }
        }
        permissionList.addAll(additionalPermissions);
        String permission = String.join(",", permissionList);
        Integer id  = Integer.valueOf(accountParam.getId());
        SysUsers sysUsers = new SysUsers();
        sysUsers.setSysUserId(id);
        SysUsers sysUsersInfo = accountMapper.getSysUserById(sysUsers);
        sysUsersInfo.setSysUserId(id);
        sysUsersInfo.setUsername(accountParam.getUsername());
        sysUsersInfo.setName(accountParam.getName());
        sysUsersInfo.setPhone(accountParam.getPhone());
        sysUsersInfo.setPermission(permission);
        int  i = accountMapper.editAccount(sysUsersInfo);
        if(i == 1){
            return ResultUtils.success();
        }
        return ResultUtils.fail(CodeEnum.EDIT_FAIL);
    }

    @Override
    public MsgResponse resetAccount(AccountParam accountParam) {
        SysUsers sysUsers = new SysUsers();
        sysUsers.setSysUserId(Integer.valueOf(accountParam.getId()));
        SysUsers sysUserInfo = accountMapper.getSysUserById(sysUsers);
        String password = MD5Util.MD5(sysUserInfo.getUsername());
        sysUserInfo.setPassword(password);
        int i = accountMapper.editAccount(sysUserInfo);
        if(i == 1){
            return ResultUtils.success();
        }
        return ResultUtils.fail(CodeEnum.EDIT_FAIL);
    }

    @Override
    public MsgResponse freezeAccount(AccountParam accountParam) {
        SysUsers sysUsers = new SysUsers();
        sysUsers.setSysUserId(Integer.valueOf(accountParam.getId()));
        SysUsers sysUserInfo = accountMapper.getSysUserById(sysUsers);
        sysUserInfo.setFreeze(Integer.valueOf(accountParam.getKind()));
        int i = accountMapper.editAccount(sysUserInfo);
        if(i == 1){
            return ResultUtils.success();
        }
        return ResultUtils.fail(CodeEnum.EDIT_FAIL);
    }

    @Override
    public MsgResponse delAccount(Integer id) {
        SysUsers sysUsers = new SysUsers();
        sysUsers.setSysUserId(id);
        SysUsers sysUserInfo = accountMapper.getSysUserById(sysUsers);
        sysUserInfo.setStatus(1);
        int i = accountMapper.editAccount(sysUserInfo);
        if(i ==1){
            return ResultUtils.success();
        }
        return ResultUtils.fail(CodeEnum.DEL_FAIL);
    }

    private String getUsernameById(Integer id) {
        SysUsers sysUsers = new SysUsers();
        sysUsers.setSysUserId(id);
        SysUsers sysUserInfo = accountMapper.getSysUserById(sysUsers);
        if(sysUserInfo == null){
            throw new CustomException(300011,"没有该用户");
        }
        return sysUserInfo.getUsername();
    }



}
